package com.jikangjun.disk.myshare.control;

import com.alibaba.fastjson.JSON;
import com.jikangjun.disk.mybatis.flexigrid.PagingEntity;
import com.jikangjun.disk.mybatis.flexigrid.TblResponseEntity;
import com.jikangjun.disk.myshare.entity.SearchShareEntity;
import com.jikangjun.disk.myshare.entity.ShareEntity;
import com.jikangjun.disk.myshare.service.ShareService;
import com.jikangjun.disk.spring.control.BaseController;
import com.jikangjun.disk.spring.security.UserDiskEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 分享控制器
 */
@Controller
@RequestMapping("/share")
public class ShareController extends BaseController {

    @Resource
    private ShareService shareService;

    // 让logger可见
    protected org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger(this.getClass());

    /**
     * 我的分享页面映射，对应路径：/disk/myshare/mySharePage
     */
    @RequestMapping("/mySharePage")
    public String mySharePage() {
        return "myshare/mySharePage";
    }

    /**
     * 分页查询分享记录
     */
    @RequestMapping(value = "/queryMyShareList", method = RequestMethod.POST)
    @ResponseBody
    public String queryShareList(@RequestParam("page") Integer page,
                                 @RequestParam("pageSize") Integer pageSize,
                                 @RequestParam(value = "fileName", required = false) String fileName,
                                 @RequestParam(value = "startTime", required = false) String startTime,
                                 @RequestParam(value = "endTime", required = false) String endTime,
                                 @RequestParam(value = "status", required = false) Integer status) {

        try {
            // 获取当前用户
            UserDiskEntity userDiskEntity = (UserDiskEntity) SecurityContextHolder.getContext()
                    .getAuthentication().getPrincipal();

            // 构建查询条件
            SearchShareEntity entity = new SearchShareEntity(userDiskEntity.getUserUuid());
            entity.setFileName(fileName);
            entity.setStatus(status);

            // 设置时间范围
            if (startTime != null && !startTime.isEmpty()) {
                entity.setStartTime(parseDate(startTime));
            }
            if (endTime != null && !endTime.isEmpty()) {
                entity.setEndTime(parseDate(endTime));
            }

            // 分页参数
            PagingEntity paging = new PagingEntity();
            paging.setPage(page);
            paging.setRp(pageSize);

            // 查询数据
            TblResponseEntity<ShareEntity> result = shareService.queryShareInfoListByPage(entity, paging);

            return JSON.toJSONString(result);

        } catch (Exception e) {
            logger.error("查询分享记录失败", e);
            return failJson("share.query.fail");
        }
    }

    /**
     * 取消分享
     */
    @RequestMapping(value = "/cancelShare", method = RequestMethod.POST)
    @ResponseBody
    public String cancelShare(@RequestParam("shareId") String shareId) {
        try {
            shareService.cancelShare(shareId);
            return successJson("share.cancel.success");
        } catch (Exception e) {
            logger.error("取消分享失败", e);
            return failJson("share.cancel.fail");
        }
    }

    /**
     * 批量取消分享
     */
    @RequestMapping(value = "/cancelShareBatch", method = RequestMethod.POST)
    @ResponseBody
    public String cancelShareBatch(@RequestParam("shareIds") String shareIds) {
        try {
            String[] ids = shareIds.split(",");
            shareService.cancelShareBatch(ids);
            return successJson("share.cancel.batch.success");
        } catch (Exception e) {
            logger.error("批量取消分享失败", e);
            return failJson("share.cancel.batch.fail");
        }
    }

    /**
     * 删除分享记录
     */
    @RequestMapping(value = "/deleteShare", method = RequestMethod.POST)
    @ResponseBody
    public String deleteShare(@RequestParam("shareId") String shareId) {
        try {
            shareService.deleteShare(shareId);
            return successJson("share.delete.success");
        } catch (Exception e) {
            logger.error("删除分享记录失败", e);
            return failJson("share.delete.fail");
        }
    }

    /**
     * 批量删除分享记录
     */
    @RequestMapping(value = "/deleteShareBatch", method = RequestMethod.POST)
    @ResponseBody
    public String deleteShareBatch(@RequestParam("shareIds") String shareIds) {
        try {
            String[] ids = shareIds.split(",");
            shareService.deleteShareBatch(ids);
            return successJson("share.delete.batch.success");
        } catch (Exception e) {
            logger.error("批量删除分享记录失败", e);
            return failJson("share.delete.batch.fail");
        }
    }

    /**
     * 更新分享信息
     */
    @RequestMapping(value = "/updateShare", method = RequestMethod.POST)
    @ResponseBody
    public String updateShare(@RequestParam("shareId") String shareId,
                              @RequestParam(value = "description", required = false) String description,
                              @RequestParam(value = "expireTime", required = false) String expireTime) {
        try {
            ShareEntity entity = shareService.queryShareInfoById(shareId);
            if (entity == null) {
                return failJson("share.not.exist");
            }

            entity.setDescription(description);
            if (expireTime != null && !expireTime.isEmpty()) {
                entity.setExpireTime(parseDate(expireTime));
            }

            shareService.updateShareInfo(entity);
            return successJson("share.update.success");
        } catch (Exception e) {
            logger.error("更新分享信息失败", e);
            return failJson("share.update.fail");
        }
    }

    /**
     * 复制分享链接
     */
    @RequestMapping(value = "/copyShareLink", method = RequestMethod.POST)
    @ResponseBody
    public String copyShareLink(@RequestParam("shareId") String shareId) {
        try {
            ShareEntity entity = shareService.queryShareInfoById(shareId);
            if (entity == null) {
                return failJson("share.not.exist");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("shareLink", entity.getShareLink());
            result.put("shareCode", entity.getShareCode());

            Map<String, Object> rspMap = new HashMap<>();
            rspMap.put("success", true);
            rspMap.put("msg", "获取分享链接成功");
            rspMap.put("data", result);
            return JSON.toJSONString(rspMap);
        } catch (Exception e) {
            logger.error("获取分享链接失败", e);
            return failJson("share.copy.fail");
        }
    }

    /**
     * 解析日期字符串
     */
    private Date parseDate(String dateStr) {
        try {
            return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
        } catch (Exception e) {
            try {
                return new java.text.SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
            } catch (Exception ex) {
                return null;
            }
        }
    }
}
